<template>
    <el-upload :accept="accept" :action="url() + (path ? '/' + path : '')" :auto-upload="autoUpload"
               :before-upload="beforeUpload"
               :headers="getHeaders()"
               :on-success="handleUploaded" :show-file-list="false" ref="uploader">
        <el-button :size="size" :type="type">{{label}}</el-button>
    </el-upload>
</template>
<script lang="ts">
  import {BASE_URL} from '@/api/upload/uploadApi';
  import FileInfo from '@/structure/fileInfo';
  import Result from '@/structure/result';
  import UserUtil from '@/utils/user';
  import {ElUpload} from 'element-ui/types/upload';
  import {Component, Prop, Vue} from 'vue-property-decorator';

  @Component
  export default class UploadSingle extends Vue {

    @Prop({
      default: ''
    })
    public path!: string;
    @Prop({
      default: null
    })
    public accept!: string;
    @Prop({
      default: null
    })
    public onSuccess!: (res: FileInfo | undefined) => void;
    @Prop({
      default: null
    })
    public onFail?: () => void;
    @Prop({
      default: 'small'
    })
    public size!: string;
    @Prop({
      default: 'primary'
    })
    public type!: string;
    @Prop({
      default: '上传'
    })
    public label!: string;
    @Prop({
      default: true
    })
    public autoUpload!: boolean;
    @Prop()
    public beforeUpload!: (file: File) => (boolean | Promise<any>);

    public handleUploaded(res: Result<FileInfo>): void {
      if (res.status) {
        if (this.onSuccess && typeof this.onSuccess === 'function') {
          this.onSuccess(res.data);
        }
      } else {
        if (this.onFail && typeof this.onFail === 'function') {
          this.onFail();
        }
      }
    }

    public submit(): void {
      (this.$refs.uploader as ElUpload).submit();
    }

    public url(): string {
      return process.env.VUE_APP_API_URL + `/${BASE_URL}/single`;
    }

    public getHeaders(): object {
      const token = UserUtil.getAccessToken();
      return {
        Authorization: token ? token : '' as string
      };
    }
  }
</script>
<style scoped>
</style>
